package csu.softwaremetric.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import csu.softwaremetric.entity.InfoFlow;
import csu.softwaremetric.service.InfoFlowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.util.List;

@Controller
public class InfoFlowController {
    File dest;

    @Autowired
    private InfoFlowService infoFlowService;

    @GetMapping("/infoFlow/{name}")
    @ResponseBody
    public ResponseEntity<JSONArray> getInfoFlow(@PathVariable String name) {
        String path = "upload/Code/" + name;
        List<InfoFlow> methods = infoFlowService.getInfoFlows(path);

        if (methods == null) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("STATUS", "FAILURE");
            jsonObject.put("MSG", "文件不存在");
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(jsonObject);
            return new ResponseEntity<>(jsonArray, HttpStatus.BAD_REQUEST);
        }

        JSONArray jsonArray = new JSONArray();
        for(InfoFlow method : methods)
        {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("methodName", method.getMethodName());
            jsonObject.put("flowIn", method.getFlowIn());
            jsonObject.put("flowOut", method.getFlowOut());
            jsonObject.put("length", method.getLength());
            jsonObject.put("complexity", method.getComplexity());
            jsonObject.put("shepperdComplexity", method.getShepperdComplexity());
            jsonObject.put("startLine", method.getStartLine());
            jsonObject.put("endLine", method.getEndLine());
            jsonObject.put("source", method.getSource());
            jsonArray.add(jsonObject);
        }

        return new ResponseEntity<>(jsonArray, HttpStatus.OK);
    }
}
